<template>
  <div class="center-wrap con-wrap">
    <h2>{{ templateData.templateName }}</h2>
    <div class="content drop">
      <form-comp
        v-model:formItem="formItem"
        v-model:formData="formData"
        @onClickFormItem="onClickFormItem"
      >
        <template v-slot:title="{ column }">
          <div class="title-slot flex-yc">
            <el-input
              class="input"
              v-model="column.value[0]"
              placeholder="请输入文字"
            ></el-input>
            <el-input
              class="input"
              v-model="column.value[1]"
              placeholder="请输入文字"
            ></el-input>
          </div>
        </template>
        <template v-slot:table="{ column }">
          <table>
            <tr class="input-bgc">
              <th v-for="(col, i) in column.tableThContent" :key="i">
                <el-input v-model="column.tableThContent[i]" />
              </th>
            </tr>
            <tr v-for="(cols, row) in column.tableContent" :key="row">
              <td v-for="(col, coli) in cols" :key="coli">
                <el-input v-model="column.tableContent[row][coli]" />
              </td>
            </tr>
          </table>
        </template>
      </form-comp>
    </div>
    <div class="flex" style="justify-content: center; margin: 10px 0">
      <el-button type="primary" @click="onSubmitTemplate">保存</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import FormComp from '@/components/form/form.vue'
import {
  findParentElement,
  MsgError,
  MsgSuccess,
  randomString,
} from '@/utils/utils.ts'
import {
  formItemType,
  HTMLElementEvent,
  OptionFormDataType,
  queryFormItemType,
} from '../template/type'
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import emitter from '@/utils/emitter.ts'
import {
  dataBaseTemplateDetail,
  reqDataBaseTemplateBody,
  respDataBaseTemplate,
} from '@/api/types/database'
import {
  reqAddOrUpdateDataBaseTemplate,
  reqGetDataBaseTemplate,
} from '@/api/database.ts'
import { useRouter } from 'vue-router'
const router = useRouter()

const props = defineProps<{
  templateData: respDataBaseTemplate
  article?: boolean
  designFormItem?: formItemType[]
}>()

onMounted(() => {
  emitter.on('onDblclickComp', onDblclickComp)
  emitter.on('onChangeFormItem', onChangeFormItem)
  emitter.on('onCustomItemMove', onCustomItemMove)
})
onUnmounted(() => {
  emitter.off('onDblclickComp')
  emitter.off('onChangeFormItem')
  emitter.off('onCustomItemMove')
})

const formData = reactive({})
const formItem = ref<formItemType[]>([])
const formItemKey = ref<string>('')
const onDblclickComp = (item: queryFormItemType) => {
  formItemKey.value = randomString(5)
  formItem.value.push({
    key: formItemKey.value,
    type: item.type,
    label: item.label,
    prop: formItemKey.value,
    style: { height: item.height || '', tool: item.tool || '' },
    slotName: item.slotName || '',
    value: [],
    tableThContent: [],
    tableContent: [],
  })
}

// 改变属性
const onChangeFormItem = (val: OptionFormDataType) => {
  formItem.value.forEach((item) => {
    if (item.key === formItemKey.value) {
      item.label = val.title
      item.placeholder = val.tip
      item.bgColor = val.backgroundColor
      item.order = val.order
      item.description = val.explain
      if (item.slotName === 'table') {
        const row = Number(val.table[0])
        const column = Number(val.table[1])
        const rowStep = row - (item.tableContent?.length || 0)
        const columnStep = column - (item.tableThContent?.length || 0)
        if (columnStep > 0) {
          item.tableThContent = item.tableThContent?.length
            ? [...item.tableThContent, ...new Array(columnStep).fill('')]
            : new Array(columnStep).fill('')

          item.tableContent = item.tableContent?.length
            ? item.tableContent?.map((col) => {
                col = [...col, ...new Array(columnStep).fill('')]
                return col
              })
            : item.tableContent?.map((col) => {
                col = new Array(columnStep).fill('')
                return col
              })
        } else {
          item.tableThContent = item.tableThContent?.slice(
            0,
            item.tableThContent?.length + columnStep,
          )
          item.tableContent = item.tableContent?.map((col) => {
            col = col.slice(0, col.length + columnStep)
            return col
          })
        }
        if (rowStep > 0) {
          item.tableContent = item.tableContent?.length
            ? [
                ...item.tableContent,
                ...new Array(rowStep).fill(new Array(column).fill('')),
              ]
            : new Array(rowStep).fill(new Array(column).fill(''))
        } else {
          item.tableContent = item.tableContent?.slice(
            0,
            item.tableContent?.length + rowStep,
          )
        }
        item.row = row + ''
        item.column = column + ''
      }
      item.spacing = val.spacing
    }
  })
}

// 点击上移下移
const onCustomItemMove = (type: string) => {
  const formItemIndex = formItem.value.findIndex(
    (item) => item.key === formItemKey.value,
  )
  if (type === 'del') return formItem.value.splice(formItemIndex, 1)
  if (type === 'up' && formItemIndex === 0) return
  if (type === 'down' && formItemIndex === formItem.value.length - 1) return

  const formDelItem = formItem.value.splice(formItemIndex, 1)
  if (type === 'up') formItem.value.splice(formItemIndex - 1, 0, ...formDelItem)
  if (type === 'down')
    formItem.value.splice(formItemIndex + 1, 0, ...formDelItem)
}

// 点击组件选项
const onClickFormItem = (
  val: formItemType,
  el: HTMLElementEvent<HTMLElement>,
) => {
  formItemKey.value = val.key
  const formItemChildEl = document.getElementById(el.target.id)
  const formItemEl = findParentElement(formItemChildEl, 'el-form-item')
  document.querySelectorAll('.el-form-item').forEach((item: Element) => {
    item.style.boxShadow = 'none'
  })
  formItemEl.style.boxShadow = 'rgb(0 0 0 / 10%) 0 0 36px'
  emitter.emit('onChangeOptionFormData', val)
}

// 获取模板信息
const getDataBaseTemplate = async () => {
  const { data } = await reqGetDataBaseTemplate({ id: props.templateData.id })
  if (data.length > 0) {
    const templateDetails: dataBaseTemplateDetail[] = JSON.parse(
      data[0].templateDetails,
    )
    const templateData = []
    templateDetails.forEach((item) => {
      if (item.description) templateData.push(JSON.parse(item.description))
    })
    formItem.value = templateData
  }
}

watch(
  () => props.templateData.id,
  (val) => {
    formItem.value = []
    getDataBaseTemplate()
  },
  {
    immediate: true,
  },
)

// 提交
const onSubmitTemplate = async () => {
  if (props.article) {
    emitter.emit('designFormItem', formItem.value)
    return false
  }
  const reqData: reqDataBaseTemplateBody = {
    templateName: props.templateData.templateName,
    templateCategory: props.templateData.templateCategory,
    templateDetails: [],
    templateStatus: 0,
  }
  if (props.templateData.id) reqData.id = props.templateData.id
  formItem.value.forEach((item, key) => {
    if (formData[item.prop]) item.value = formData[item.prop]
    reqData.templateDetails?.push({
      sequence: key,
      type: item.type,
      titleName: item.label,
      placeholder: item.placeholder || '',
      backgroundColor: item.bgColor || '',
      description: JSON.stringify(item),
      row: item.row || '',
      column: item.column || '',
      spacing: item.spacing || '',
    })
  })
  const { code, msg } = await reqAddOrUpdateDataBaseTemplate(reqData)
  if (code === 0) {
    MsgSuccess(msg || '添加成功')
    router.back()
  } else MsgError(msg || '添加失败')
}
</script>

<style scoped lang="scss">
.center-wrap {
  width: 1130px;

  h2 {
    font-size: 24px;
    color: #021429;
    text-align: center;
  }

  .drop {
    width: 100%;
    min-height: 80%;

    .title-slot {
      width: 100%;
      background-color: #d4d6d9;
      justify-content: space-between;

      .input {
        width: 250px;
      }
    }
  }
}
</style>
